<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="用户名称" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入用户名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="用户状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:couser:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:couser:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:couser:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="用户编号" align="center" prop="id"/>
      <el-table-column label="用户名称" align="center" prop="username"/>
      <el-table-column label="用户姓名" align="center" prop="name"/>
      <el-table-column label="手机号码" align="center" prop="phone"/>
      <el-table-column label="邮箱" align="center" prop="email"/>
      <el-table-column label="学校" align="center" prop="school"/>
      <el-table-column label="学院" align="center" prop="college"/>
      <el-table-column label="专业" align="center" prop="major"/>
      <el-table-column label="学号" align="center" prop="studentId"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:couser:edit']">修改</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:couser:remove']">删除</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-key" @click="handleResetPwd(scope.row)"
            v-hasPermi="['system:couser:resetPwd']">重置密码</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-data-line" @click="handleStats(scope.row)"
            v-hasPermi="['system:contract:list']">统计</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList"/>

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名称" prop="username" v-if="form.id == undefined">
          <el-input v-model="form.username" placeholder="请输入用户名称"/>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="form.id == undefined">
          <el-input v-model="form.password" placeholder="请输入用户密码" type="password"/>
        </el-form-item>
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入用户姓名"/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="学校" prop="school">
          <el-input v-model="form.school" placeholder="请输入学校"/>
        </el-form-item>
        <el-form-item label="学院" prop="college">
          <el-input v-model="form.college" placeholder="请输入学院"/>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="form.major" placeholder="请输入专业"/>
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学号"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户合同统计对话框 -->
    <el-dialog :title="stats.title" :visible.sync="stats.open" width="800px" append-to-body>
      <el-card class="box-card mb20">
        <div class="statistics-container">
          <div class="stat-item">
            <span class="label">合同总数</span>
            <span class="value">{{ stats.data.total || 0 }}</span>
          </div>
          <el-divider direction="vertical"></el-divider>
          <div class="stat-item">
            <span class="label">处理中</span>
            <span class="value warning-text">{{ (stats.data.uploadingCount || 0) + (stats.data.analyzingCount || 0) }}</span>
          </div>
          <el-divider direction="vertical"></el-divider>
          <div class="stat-item">
            <span class="label">已完成</span>
            <span class="value success-text">{{ stats.data.completedCount || 0 }}</span>
          </div>
          <el-divider direction="vertical"></el-divider>
          <div class="stat-item">
            <span class="label">失败</span>
            <span class="value danger-text">{{ stats.data.failCount || 0 }}</span>
          </div>
        </div>
      </el-card>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <div ref="riskChart" style="height: 300px; padding: 20px;"></div>
        </el-col>
        <el-col :span="12">
          <div ref="typeChart" style="height: 300px; padding: 20px;"></div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect
} from "@/api/system/couser";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as echarts from 'echarts'
import { getContractStats, getContractTypeStats } from "@/api/system/contract";

export default {
  name: "CoUser",
  components: { Treeselect },
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "导入用户数据",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/couser/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: undefined,
        phone: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: '用户密码长度必须介于 6 和 20 之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: "邮箱地址不能为空", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: ['blur', 'change'] }
        ],
        phone: [
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ]
      },
      // 统计数据
      stats: {
        open: false,
        title: "",
        data: {},
        charts: {
          risk: null,
          type: null
        }
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        username: undefined,
        password: undefined,
        name: undefined,
        phone: undefined,
        email: undefined,
        school: undefined,
        college: undefined,
        major: undefined,
        studentId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + ids + '"的数据项？').then(function() {
        return delUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.username + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{6,20}$/,
        inputErrorMessage: "用户密码长度必须介于 6 和 20 之间"
      }).then(({ value }) => {
        resetUserPwd(row.id, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {});
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    /** 提交上传文件 */
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/system/couser/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
    },
    /** 统计按钮操作 */
    async handleStats(row) {
      this.stats.title = row.username + " 的合同统计";
      this.stats.open = true;
      
      // 获取统计数据
      const stats = await getContractStats(row.id);
      const typeStats = await getContractTypeStats(row.id);
      this.stats.data = stats.data;
      
      // 在nextTick中初始化图表，确保DOM已经渲染
      this.$nextTick(() => {
        // 初始化风险分布图表
        if (!this.stats.charts.risk) {
          this.stats.charts.risk = echarts.init(this.$refs.riskChart);
        }
        this.stats.charts.risk.setOption({
          title: { 
            text: '风险等级分布',
            left: 'center',
            top: 0,
            textStyle: {
              color: '#303133',
              fontSize: 16,
              fontWeight: 'normal'
            }
          },
          tooltip: { 
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: { 
            orient: 'horizontal',
            bottom: '0',
            itemWidth: 12,
            itemHeight: 12,
            textStyle: {
              color: '#606266',
              fontSize: 12
            }
          },
          series: [{
            name: '风险等级',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 4,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c}\n{d}%',
              fontSize: 12
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 10
            },
            data: [
              { value: stats.data.lowRiskCount || 0, name: '低风险', itemStyle: { color: '#67C23A' } },
              { value: stats.data.mediumRiskCount || 0, name: '中风险', itemStyle: { color: '#E6A23C' } },
              { value: stats.data.highRiskCount || 0, name: '高风险', itemStyle: { color: '#F56C6C' } }
            ]
          }]
        });
        
        // 初始化合同类型图表
        if (!this.stats.charts.type) {
          this.stats.charts.type = echarts.init(this.$refs.typeChart);
        }
        this.stats.charts.type.setOption({
          title: { 
            text: '合同类型分布',
            left: 'center',
            top: 0,
            textStyle: {
              color: '#303133',
              fontSize: 16,
              fontWeight: 'normal'
            }
          },
          tooltip: { 
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: { 
            orient: 'horizontal',
            bottom: '0',
            itemWidth: 12,
            itemHeight: 12,
            textStyle: {
              color: '#606266',
              fontSize: 12
            }
          },
          series: [{
            name: '合同类型',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 4,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c}\n{d}%',
              fontSize: 12
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 10
            },
            data: typeStats.data.map((item, index) => ({
              name: item.typeName,
              value: item.count,
              itemStyle: {
                color: [
                  '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', 
                  '#909399', '#B983FF', '#19CAAD', '#8CC7B5'
                ][index % 8]
              }
            }))
          }]
        });
      });
    }
  }
};
</script>

<style scoped>
.statistics-container {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 10px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 15px;
}

.stat-item .label {
  font-size: 13px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-item .value {
  font-size: 20px;
  font-weight: bold;
}

.warning-text {
  color: #E6A23C;
}

.success-text {
  color: #67C23A;
}

.danger-text {
  color: #F56C6C;
}

.mb20 {
  margin-bottom: 20px;
}
</style>
